package edu.gzy.rpsm_property.mapper;

import com.github.pagehelper.Page;
import edu.gzy.rpsm_property.pojo.Room;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

@Mapper
@Repository
public interface RoomMapper {

    @Select("SELECT * FROM room WHERE room_id = #{id}")
    Room roomById(Integer id);

    @Select("SELECT room_id, room_code FROM room WHERE room_floor_id = #{id}")
    List<Room> roomsOfFloor(Integer roomId);

    @Insert("<script>" +
            "INSERT INTO room VALUES " +
            "<foreach collection='list' item='item' index='i' separator=','> " +
            "(#{item.room_id}, #{item.room_floor_id}, #{item.built_up_area}, 4, CONCAT(#{item.room_code}, #{i} + 1))" +
            "</foreach>" +
            "</script>")
    @Options(useGeneratedKeys = true, keyProperty = "room_id", keyColumn = "room_id")
    int insertRooms(List<Room> room);

    @Select("<script>" +
            "SELECT room_id, room_floor_id, built_up_area, room_status, room_code, building_name " +
            "FROM room, floor, building " +
            "<trim prefix='WHERE' suffix='AND room.room_floor_id = floor.floor_id AND floor.belong_building = building.building_id' prefixOverrides='AND'>" +
            "<if test='floorId != null and floorId != \"\"'> AND room_floor_id = #{floorId}</if>" +
            "<if test='builtArea != null and builtArea != \"\"'> AND built_up_area = #{builtArea}</if>" +
            "<if test='status != null and status != \"\"'> AND room_status = #{status}</if>" +
            "<if test='buildingNumber != null and buildingNumber != \"\"'> AND room_code LIKE CONCAT(#{buildingNumber}, '-%')</if>" +
            "<if test='floorNumber != null and floorNumber != \"\"'> AND room_code LIKE CONCAT('%-', #{floorNumber}, '-%')</if>" +
            "</trim>" +
            "</script>")
    @Results(id = "baseWithBuildingName", value = {
            @Result(column = "building_name", property = "building_name")
    })
    Page<Room> pageOfRooms(Map<String, String> map);

    @Update("<script>UPDATE room SET room_status = #{status} WHERE room_id IN " +
            "<foreach open='(' close=')' collection='idList' item='i' separator=','>" +
            "#{i}" +
            "</foreach>" +
            "</script>")
    int changeRoomStatus(@Param("idList") List<Integer> idList, @Param("status") int status);

}
